package com.adee.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;

public class FileChannelTest {
    public static void main(String[] args) throws Exception {
        String str = "hello,尚硅谷";
        byte[] bytes = str.getBytes(StandardCharsets.UTF_8);
        FileOutputStream fileOutputStream =
                new FileOutputStream(FileChannelTest.class.getResource("/txt/hello.txt").getFile());
        FileChannel channel = fileOutputStream.getChannel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(30);
        byteBuffer.put(bytes); // 写buffer
        byteBuffer.flip();
        channel.write(byteBuffer); // 读buffer
        fileOutputStream.close();
    }

    // 当所拷贝的文件小于2G时
    public void channelCopy(String sourcePath,String destPath){
        FileChannel sourceChannel=null;
        FileChannel destChannel=null;
        try {
            sourceChannel = new FileInputStream(sourcePath).getChannel();
            destChannel = new FileOutputStream(destPath).getChannel();
            sourceChannel.transferTo(0,sourceChannel.size(),destChannel);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (sourceChannel!=null){
                    sourceChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (destChannel!=null){
                    destChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    //超过 2g 大小的文件传输
    public void channelCopy2(String sourcePath,String destPath){

        FileChannel sourceChannel=null;
        FileChannel destChannel=null;
        try {
            sourceChannel = new FileInputStream(sourcePath).getChannel();
            destChannel = new FileOutputStream(destPath).getChannel();

            long size=sourceChannel.size();
            for (long left=size;left>0;){
                long transferSize = sourceChannel.transferTo((size - left), left, destChannel);
                left=left-transferSize;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if (sourceChannel!=null){
                    sourceChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

            try {
                if (destChannel!=null){
                    destChannel.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
